package org.example3;

import org.example.Person;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;

public class SerializerUtil {

  static   String sendObj = "我是客户端,Abc123";
 static    String sendObj2 = "我是客户端,Abc123";

    public static void main(String[] args) throws Exception {


        byte[] serialBytes = serialize2ByteArray(sendObj);
        System.out.println("serialBytes.length is " +serialBytes.length);
        System.out.println("serialBytes:"+Arrays.toString(serialBytes));

        System.out.println();
        byte[] strGetBytes = sendObj2.getBytes();
        System.out.println("strGetBytes.length is " +strGetBytes.length);
        System.out.println("strGetBytes:"+Arrays.toString(strGetBytes));



//        Person person = new Person("时春跃");
//
//        byte[] bytes = serialize2ByteArray(person);
//        System.out.println(bytes.length);
//        System.out.println(Arrays.toString(bytes));
//
//        byte[] bytesObject = {-84, -19, 0, 5, 115, 114, 0, 18, 111, 114, 103, 46, 101, 120, 97, 109, 112, 108, 101, 46, 80, 101, 114, 115, 111, 110, -44, 65, -29, 115, -108, 33, 40, -75, 2, 0, 1, 76, 0, 4, 110, 97, 109, 101, 116, 0, 18, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 83, 116, 114, 105, 110, 103, 59, 120, 112, 116, 0, 9, -26, -105, -74, -26, -104, -91, -24, -73, -125};
//
//        Object object = deserialize2Object(bytesObject);
//
//        System.out.println(object);

    }

    /**
     *  将一个对象序列化为一个字节数组
     *   对象 ---> 字节数组
     * @param obj
     * @return
     * @throws Exception
     */
    public static byte[] serialize2ByteArray(Object obj) throws Exception {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(obj);

        return baos.toByteArray();
    }

    /**
     *  将一个字节数组反序列化为一个对象
     *  字节数组 ---> 对象
     * @param bytes
     * @return
     * @throws Exception
     */
    public static Object deserialize2Object(byte[] bytes) throws Exception {

        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        ObjectInputStream ois = new ObjectInputStream(bais);

        return ois.readObject();
    }


  /**
     *  将一个字节数组的一部分反序列化为一个对象
     *  字节数组部分 ---> 对象
     * @param bytes
     * @return
     * @throws Exception
     */
    public static Object deserialize2Object(byte[] bytes,int offset,int len) throws Exception {

        byte[] bytes1 = new byte[len - offset];
        for (int i = 0; i < bytes1.length; i++) {
            bytes1[i] = bytes[offset + i];
        }

        ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
        ObjectInputStream ois = new ObjectInputStream(bais);

        return ois.readObject();
    }


}
